package com.juc.juc_project.atomic;

import lombok.extern.slf4j.Slf4j;

import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by fangjicai on 2020/3/18.
 */
@Slf4j
@ThreadSafe
public class ConcurrencyTest3 {

    //请求总数
    public static  int clientTotal=5000;
    //同时并发执行的线程数
    public static int threadTotal=200;
    //public static int count=0;
    //public static AtomicInteger count=new AtomicInteger(0);
    public static AtomicLong count=new AtomicLong(0);

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();
        //定义信号量对象，允许并发环境下最大200并发访问--限流
        Semaphore semaphore = new Semaphore(threadTotal);
        //实现5000次任务执行完毕后打印相关信息
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for(int i=0;i<clientTotal;i++){
            executorService.execute(()->{
                try {
                    //申请资源
                    semaphore.acquire();
                    add();
                    //释放线程资源
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exception:",e);
                }
                //对count进行减数处理
                countDownLatch.countDown();
            });
        }
        //当前线程等待循环任务中其他线程执行完毕，在执行
        countDownLatch.await();
        //释放线程池资源
        executorService.shutdown();
        log.info("count:{}",count.get());

    }
    private static void add(){
        //count.incrementAndGet();
        //获取原来值，并增加1
        count.getAndIncrement();
    }
}
